package com.jk.util.quartz;

import com.jk.util.JsonUtil;
import com.jk.util.StringUtil;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by yanghuan on 15-8-31.
 */
public class ConcurrentJob implements Job {

    private static Logger logger = Logger.getLogger(ConcurrentJob.class);

    public ConcurrentJob() {

    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        Trigger trigger = context.getTrigger();
        JobDataMap jobDataMap = trigger.getJobDataMap();
        String beanName = jobDataMap.getString("beanName");
        try {
            if (!StringUtil.isEmpty(beanName)) {
                SchedulerContext schedulerContext = context.getScheduler().getContext();
                //获取Spring中的上下文
                ApplicationContext applicationContext = (ApplicationContext) schedulerContext.get("applicationContext");
                Class<?> targetClass = applicationContext.getType(beanName);
                Object object = targetClass.newInstance();
                Method[] methods = targetClass.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(TriggerMethod.class)) {
                        jobDataMap.remove("beanName");
                        String data = JsonUtil.toString(jobDataMap);
                        method.invoke(object, data);
                    }
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

